package zhh.tangbao.system.aop;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import zhh.tangbao.system.annotation.Authority;
import zhh.tangbao.system.annotation.WeChatTokenAccess;
import zhh.tangbao.system.constant.AuthorityModel;
import zhh.tangbao.system.constant.CommonConstant;
import zhh.tangbao.system.exception.ReEntryException;
import zhh.tangbao.system.exception.ServiceException;
import zhh.tangbao.system.utils.HttpServletRequestUtil;
import zhh.tangbao.system.utils.UserHolderUtil;
import zhh.tangbao.system.utils.WeChatUserHolderUtil;
import zhh.tangbao.user.cache.UserCache;
import zhh.tangbao.user.vo.UserVo;
import zhh.tangbao.wechat.cache.WeChatCache;
import zhh.tangbao.wechat.dao.WeChatUserDao;
import zhh.tangbao.wechat.vo.WeChatUserCacheVo;

import java.util.Set;

/**
 * 2023/2/27
 * @author 粥灰灰
 * @version 1.0
 * 描述
 */

@Component
@Aspect
@Order(value = 1)
public class WeChatTokenAccessAop {


    @Autowired
    private WeChatUserDao weChatUserDao;

    @Autowired
    private WeChatCache weChatCache;

    @Autowired
    private WeChatUserHolderUtil weChatUserHolderUtil;

    @Pointcut("@annotation(zhh.tangbao.system.annotation.WeChatTokenAccess)")
    public void weChatToken() {
    }

    @Before(value = "@annotation(weChatToken)")
    public void before(WeChatTokenAccess weChatToken) {
        // 微信小程序的功能在不需要登录的时候不会使用用户信息，所以可以直接return
        if (!weChatToken.login()) {
            return;
        }
        String token = HttpServletRequestUtil.getRequestHeader(CommonConstant.TOKEN);
        Assert.notBlank(token, "用户未登录");
        WeChatUserCacheVo user = weChatCache.getLoginData(token);
        // 开启补货人员权限检测
        if (weChatToken.replenishment() && user.getIsReplenishment() != 1) {
            throw new ServiceException("权限不足，无法使用该功能");
        }
        if (null == user) {
            user = weChatUserDao.getWeChatUserCacheVo(token);
            if (null == user) {
                throw new ReEntryException("登录凭证不能存在或过期，请重新登录");
            }
        }
        weChatCache.login(user);
        weChatUserHolderUtil.setCurrentUser(user);
    }
}
